﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Collections;

namespace BlueLotus7.Common
{
    public class CacheItem
    {
        bool needRefresh = true;
        DateTime? expiredStamp = null;
        object cachedObject = null;
        object locker = new object();

        /// <summary>
        /// Indicates if needs refresh.
        /// </summary>
        public bool NeedRefresh
        {
            get
            {
                lock (locker)
                {
                    return needRefresh || (expiredStamp != null && expiredStamp < DateTime.Now);
                }
            }
            set
            {
                lock (locker)
                {
                    needRefresh = true;
                }
            }
        }

        /// <summary>
        /// The object to cache.
        /// </summary>
        public object CachedObject
        {
            get
            {
                lock (locker)
                {
                    return cachedObject;
                }
            }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public CacheItem()
        {
        }

        /// <summary>
        /// Updates object to cache.
        /// </summary>
        /// <param name="cachedObject">The object to cache.</param>
        /// <param name="expiredStamp">The expired time.</param>
        public void Update(object cachedObject, DateTime? expiredStamp)
        {
            lock (locker)
            {
                needRefresh = false;
                this.expiredStamp = expiredStamp;
                this.cachedObject = cachedObject;
            }
        }

        /// <summary>
        /// Updates object to cache.
        /// </summary>
        /// <param name="cachedObject">The object to cache.</param>
        public void Update(object cachedObject)
        {
            Update(cachedObject, null);
        }
    }
}